package com.db.manage.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.db.manage.datasource.DynamicDataSource;
import com.db.manage.model.ConnectionConfig;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource createInitDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        // 属性由 @ConfigurationProperties 自动绑定（需确保前缀正确）
        return dataSource;
    }

    @Bean
    @Primary
    public DataSource defaultDataSource() throws SQLException {
        // 创建初始数据源用于创建数据库和表
        DruidDataSource initDataSource = createInitDataSource();

        // 创建数据库和表
        try (var conn = initDataSource.getConnection()) {
            try (var stmt = conn.createStatement()) {
                // 创建数据库
                stmt.execute("CREATE DATABASE IF NOT EXISTS test");
                log.info("Database 'test' created or already exists");
                
                // 切换到新创建的数据库
                stmt.execute("USE test");
                
                // 创建表
                stmt.execute("""
                    CREATE TABLE IF NOT EXISTS connection_config (
                        id VARCHAR(36) PRIMARY KEY,
                        name VARCHAR(100) NOT NULL,
                        db_type VARCHAR(20) NOT NULL,
                        url VARCHAR(500) NOT NULL,
                        username VARCHAR(100) NOT NULL,
                        password VARCHAR(100) NOT NULL,
                        driver_path VARCHAR(500),
                        version VARCHAR(20),
                        active BOOLEAN DEFAULT true,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                    )
                """);
                log.info("Table 'connection_config' created or already exists");
            }
        } catch (SQLException e) {
            log.error("Failed to create database or table", e);
            throw e;
        }
        
        // 创建最终使用的数据源
        // DruidDataSource dataSource = new DruidDataSource();
        // dataSource.setUrl("jdbc:mysql://172.16.0.134:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        // dataSource.setUsername("root");
        // dataSource.setPassword("Dataway25331");
        // dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        // 设置连接池配置
        /*initDataSource.setInitialSize(5);
        initDataSource.setMinIdle(5);
        initDataSource.setMaxActive(20);
        initDataSource.setMaxWait(60000);
        initDataSource.setTimeBetweenEvictionRunsMillis(60000);
        initDataSource.setMinEvictableIdleTimeMillis(300000);
        initDataSource.setValidationQuery("SELECT 1");
        initDataSource.setTestWhileIdle(true);
        initDataSource.setTestOnBorrow(false);
        initDataSource.setTestOnReturn(false);
        initDataSource.setPoolPreparedStatements(true);
        initDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        initDataSource.setFilters("stat,wall");
        
        // 设置数据库类型
        initDataSource.setDbType("mysql");

        initDataSource.init();*/
        return initDataSource;
    }

    @Bean
    @DependsOn("defaultDataSource")
    public JdbcTemplate jdbcTemplate(@Qualifier("defaultDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    @Primary
    @DependsOn({"defaultDataSource", "jdbcTemplate"})
    public DynamicDataSource dynamicDataSource(
            @Qualifier("defaultDataSource") DataSource defaultDataSource,
            JdbcTemplate jdbcTemplate) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("default", defaultDataSource);
        
        try {
            // 从数据库加载所有连接配置
            List<ConnectionConfig> connections = jdbcTemplate.query(
                "SELECT * FROM connection_config /*WHERE active = true*/",
                new RowMapper<ConnectionConfig>() {
                    @Override
                    public ConnectionConfig mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ConnectionConfig config = new ConnectionConfig();
                        config.setId(rs.getString("id"));
                        config.setName(rs.getString("name"));
                        config.setDbType(rs.getString("db_type"));
                        config.setUrl(rs.getString("url"));
                        config.setUsername(rs.getString("username"));
                        config.setPassword(rs.getString("password"));
                        config.setDriverPath(rs.getString("driver_path"));
                        config.setVersion(rs.getString("version"));
                        config.setActive(rs.getBoolean("active"));
                        return config;
                    }
                }
            );

            // 为每个连接配置创建数据源
            for (ConnectionConfig config : connections) {
                try {
                    DruidDataSource dataSource = new DruidDataSource();
                    dataSource.setUrl(config.getUrl());
                    dataSource.setUsername(config.getUsername());
                    dataSource.setPassword(config.getPassword());
                    dataSource.setDriverClassName(config.getDriverPath());
                    dataSource.setDbType(config.getDbType());
                    
                    // 设置连接池配置
                    dataSource.setInitialSize(5);
                    dataSource.setMinIdle(5);
                    dataSource.setMaxActive(20);
                    dataSource.setMaxWait(60000);
                    dataSource.setTimeBetweenEvictionRunsMillis(60000);
                    dataSource.setMinEvictableIdleTimeMillis(300000);
                    dataSource.setValidationQuery("SELECT 1");
                    dataSource.setTestWhileIdle(true);
                    dataSource.setTestOnBorrow(false);
                    dataSource.setTestOnReturn(false);
                    
                    // 初始化数据源
                    try {
                        dataSource.init();
                    } catch (SQLException e) {
                        log.error("初始化数据源失败: {}", config.getName(), e);
                        continue; // 跳过这个数据源，继续处理下一个
                    }
                    
                    // 添加到目标数据源
                    targetDataSources.put(config.getId(), dataSource);
                    log.info("初始化数据源成功: {}", config.getName());
                } catch (Exception e) {
                    log.error("创建数据源失败: {}", config.getName(), e);
                }
            }
        } catch (Exception e) {
            log.error("加载连接配置失败", e);
        }
        
        // 设置目标数据源
        dynamicDataSource.setTargetDataSources(targetDataSources);
        
        // 初始化动态数据源
        dynamicDataSource.afterPropertiesSet();
        
        return dynamicDataSource;
    }
} 